package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FriendService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.utils.ConstantUtil;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class MakeFriendManager {


    @DubboReference
    RecommendUserService recommendUserService;

    @DubboReference
    UserInfoService userInfoService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @DubboReference
    VisitorService visitorService;

    @DubboReference
    UserLocationService userLocationService;

    @DubboReference
    QuestionService questionService;

    @DubboReference
    FriendService friendService;



    public ResponseEntity findTodayBest() {
        //1.获取登陆者id
        Long toUserId = UserHolder.get().getId();

        //2.远程调用service查询今日最佳
        RecommendUser recommendUser = recommendUserService.findTodayBest(toUserId);

        //注意:刚注册用户有可能还没有推荐--可以随机一个,也可以固定一个
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            //设置一个随机分数(hutool中的RandomUtil)或者固定值
            recommendUser.setScore(99D);
        }

        //3.查询推荐用户的userInfo
        UserInfo userInfo = userInfoService.findByUserId(recommendUser.getUserId());

        //4.新建一个vo封装userInfo和缘分值且返回
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        recommendUserVo.setUserInfo(userInfo);
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());//缘分值

        return ResponseEntity.ok(recommendUserVo);
    }


    public ResponseEntity findRecommendUserByPage(Integer pageNum, Integer pageSize) {
        //1.调用service查询推荐给我的pageBeanVo
        PageBeanVo pageBeanVo = recommendUserService.findByPage(UserHolder.get().getId(), pageNum, pageSize);

        //2.获取pageBeanVo中推荐用户集合(id)
        List<RecommendUser> items = (List<RecommendUser>) pageBeanVo.getItems();

        //3.遍历推荐用户集合,获取每个推荐用户id,查询推荐用户userInfo,将userInfo和缘分值封装成vo,将每个vo放入一个voList中
        //3.1 创建voList,存放页面上返回的数据
        List<RecommendUserVo> voList = new ArrayList<>();

        //3.2 遍历推荐用户集合,获取每个推荐用户id
        items.forEach(recommendUser -> {
            //3.3 查询推荐用户userInfo
            UserInfo userInfo = userInfoService.findByUserId(recommendUser.getUserId());

            //3.4 将userInfo和缘分值封装成vo
            RecommendUserVo vo = new RecommendUserVo();
            vo.setUserInfo(userInfo);
            vo.setFateValue(recommendUser.getScore().longValue());

            //3.5 将每个vo放入一个voList中
            voList.add(vo);
        });

        //4.将voList设置给pageBeanVo
        pageBeanVo.setItems(voList);

        //5.返回pageBeanVo
        return ResponseEntity.ok(pageBeanVo);
    }


    public ResponseEntity findPersonalInfo(Long jiaRenId) {
        //1.调用service查询推荐用户userInfo
        UserInfo userInfo = userInfoService.findByUserId(jiaRenId);

        //2.调用service查询推荐用户缘分值
        RecommendUser recommendUser = recommendUserService.findPersonalInfo(UserHolder.get().getId(), jiaRenId);
        // 今日佳人有可能不存在,因为当前用户是新用户设置的固定的用户(NPC),所以推荐表中没有
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setScore(99D);
        }

        //3.封装RecommentUserVo且返回
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue());

        return ResponseEntity.ok(vo);
    }


    public ResponseEntity findVisitorsTop5() {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.从redis中获取当前用户上次访问时间(注意:有可能不存在上次时间)
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String timeStr = operations.get(ConstantUtil.LAST_ACCESS_TIME + userId);
        Long lastAccessTime;
        if(timeStr != null){
            lastAccessTime = Long.parseLong(timeStr);
        }else{
            //设置默认时间 1970
            lastAccessTime = new Date(0).getTime();
        }

        //3.远程调用service查询访客集合
        List<Visitor> visitors = visitorService.findVisitorsTop5(userId, lastAccessTime);

        //4.遍历访客集合,获取每个访客id,查询访客的userInfo,将userInfo和缘分值封装成visitorVo,将每个vo放入voList中
        List<VisitorVo> voList = new ArrayList<>();
        if (CollUtil.isNotEmpty(visitors)) {
            visitors.forEach(visitor -> {
                UserInfo userInfo = userInfoService.findByUserId(visitor.getVisitorUserId());

                VisitorVo vo = new VisitorVo();
                vo.setUserInfo(userInfo);
                vo.setFateValue(visitor.getScore().longValue());

                //将每个vo放入voList中
                voList.add(vo);
            });
        }

        //5.将当前时间设置为最后访问时间
        operations.set(ConstantUtil.LAST_ACCESS_TIME+userId,System.currentTimeMillis()+"");

        //6.将voList返回
        return ResponseEntity.ok(voList);
    }


    public void saveUserLocation(Double longitude, Double latitude, String addrStr) {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.远程调用service完成保存即可
        userLocationService.save(userId,longitude,latitude,addrStr);

    }


    public ResponseEntity searchNear(String gender, Integer distance) {
        //1.远程调用service获取附近的人的id集合
        Long userId = UserHolder.get().getId();
        List<Long> ids = userLocationService.searchNear(userId, distance);

        //2.遍历id集合,获取每个用户的id,查询用户的userInfo,将userInfo封装成NearUserVo对象,将每个vo放入声明好的voList中
        //2.1声明一个voList
        List<NearUserVo> voList = new ArrayList<>();

        //2.2遍历id集合,获取每个用户的id(对id进行判断的话用普通的for循环比较好)
        if (CollUtil.isNotEmpty(ids)) {
            for (Long id : ids) {
                //排除自己
                if (id.equals(userId)) {
                    continue;
                }
                //2.3查询用户的userInfo
                UserInfo userInfo = userInfoService.findByUserId(id);
                //筛选性别
                if (!gender.equals(userInfo.getGender())) {
                    continue;
                }

                //2.4将userInfo封装成NearUserVo对象
                NearUserVo vo = new NearUserVo();
                vo.setUserId(id);
                vo.setNickname(userInfo.getNickname());
                vo.setAvatar(userInfo.getAvatar());

                //2.5将每个vo放入声明好的voList中
                voList.add(vo);
            }
        }
        //3.返回voList
        return ResponseEntity.ok(voList);

    }


    public ResponseEntity findStrangerQuestion(Long userId) {
        //1.调用questionService查询用户的问题
        Question question = questionService.findByUserId(userId);

        //2.判断用户有无设置过问题,若没有则设置默认问题
        if (question == null) {
            question = new Question();
        }

        return ResponseEntity.ok(question.getStrangerQuestion());
    }


    public ResponseEntity findContactsByPage(Integer pageNum, Integer pageSize) {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.调用service查询当前页的好友数据
        PageBeanVo pageBeanVo = friendService.findContactsByPage(userId, pageNum, pageSize);

        //3.从pageBeanVo中获取好友list
        List<Friend> items = (List<Friend>) pageBeanVo.getItems();

        //4.遍历好友list,获取每个好友id,查询好友的userInfo,
        // 将userInfo和环信id封装ContactVo(注意:userId是环信id),将vo放入预先声明好的voList集合中
        List<ContactVo> voList = new ArrayList<>();

        if (CollUtil.isNotEmpty(items)) {
            items.forEach(friend -> {
                //遍历好友list,获取每个好友id
                Long friendId = friend.getFriendId();

                //查询好友的userInfo
                UserInfo userInfo = userInfoService.findByUserId(friendId);

                // 将userInfo和环信id封装ContactVo(注意:userId是环信id)
                ContactVo vo = new ContactVo();
                vo.setUserInfo(userInfo);
                //千万注意: 是环信id
                vo.setUserId("HX"+friendId);

                //放入集合
                voList.add(vo);
            });
        }

        //5.将voList赋值给pageBeanVO
        pageBeanVo.setItems(voList);

        //6.返回pageBeanVo
        return ResponseEntity.ok(pageBeanVo);
    }
}












